<script setup>
import { onMounted, reactive, ref } from 'vue'
import { fetchOperatorInfo, postAddOperator } from '@/api/operator'
import { fetchRoleList } from '@/api/roleApi'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'

const props = defineProps({
  dealerOperatorId: {
    type: String,
    default: null,
  },
})

const emit = defineEmits(['close', 'success'])

/**
 * @description 操作人员信息
 */
const operatorInfo = reactive({
  dealerOperatorId: '',
  dealerId: '',
  dealerRoleId: '', // 分配角色时用
  loginCode: '',
  loginPassword: '',
  nickname: '',
  profilePicture: '',
  phoneNumber: '',
  operatorEnabled: true,
  dealer: '',
  email: '',
  editType: '0', // 0表示新增，1表示编辑
})

/**
 * @description 角色列表
 */
const roleList = ref([])

/**
 * @description 表单引用
 */
const operatorFormRef = ref(null)

/**
 * @description 加载中状态
 */
const loading = ref(false)

/**
 * @description 是否是编辑模式
 */
const isEdit = ref(false)

/**
 * @description 表单规则
 */
const rules = {
  loginCode: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 3, max: 20, message: '登录账号长度应为3-20个字符', trigger: 'blur' },
  ],
  loginPassword: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' },
  ],
  nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
}

/**
 * @description 重置表单和数据
 */
const resetForm = () => {
  if (operatorFormRef.value) {
    operatorFormRef.value.resetFields()
  }
  Object.assign(operatorInfo, {
    dealerOperatorId: '',
    dealerId: '',
    dealerRoleId: '',
    loginCode: '',
    loginPassword: '',
    nickname: '',
    profilePicture: '',
    phoneNumber: '',
    operatorEnabled: true,
    dealer: '',
    email: '',
    editType: '0', // 重置为新增模式
  })
  isEdit.value = false
}

/**
 * @description 获取角色列表
 */
const handleFetchRoleList = async () => {
  try {
    const res = await fetchRoleList()
    if (res.success && res.data) {
      roleList.value = res.data
    } else {
      roleList.value = []
    }
  } catch (error) {
    logger.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  }
}

/**
 * @description 获取操作人员信息
 */
const handleFetchOperatorInfo = async (id) => {
  try {
    loading.value = true
    const res = await fetchOperatorInfo(id)
    if (res.success && res.data) {
      Object.assign(operatorInfo, res.data)
      // 设置为编辑模式
      operatorInfo.editType = '1'
      isEdit.value = true
    } else {
      ElMessage.error(res.msg || '获取操作人员信息失败')
    }
  } catch (error) {
    logger.error('获取操作人员信息失败', error)
    ElMessage.error('获取操作人员信息失败')
  } finally {
    loading.value = false
  }
}

/**
 * @description 提交表单
 */
const handleSubmit = async () => {
  if (!operatorFormRef.value) return

  await operatorFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        // 确保editType与当前模式一致
        operatorInfo.editType = isEdit.value ? '1' : '0'

        const res = await postAddOperator(operatorInfo)
        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          emit('success')
          emit('close')
        } else {
          ElMessage.error(res.msg || (isEdit.value ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        logger.error('保存操作人员失败', error)
        ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
      } finally {
        loading.value = false
      }
    }
  })
}

/**
 * @description 取消操作
 */
const handleCancel = () => {
  resetForm()
  emit('close')
}

onMounted(async () => {
  await handleFetchRoleList()

  if (props.dealerOperatorId) {
    await handleFetchOperatorInfo(props.dealerOperatorId)
  }
})
</script>

<template>
  <div class="add-operator-container">
    <el-form
      ref="operatorFormRef"
      :model="operatorInfo"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="登录账号" prop="loginCode">
            <el-input
              v-model="operatorInfo.loginCode"
              placeholder="请输入登录账号"
              :disabled="isEdit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="登录密码" prop="loginPassword" v-if="!isEdit">
            <el-input
              v-model="operatorInfo.loginPassword"
              type="password"
              placeholder="请输入登录密码"
              show-password
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="operatorInfo.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input v-model="operatorInfo.phoneNumber" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="operatorInfo.email" placeholder="请输入电子邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择角色" prop="dealerRoleId">
            <el-select
              v-model="operatorInfo.dealerRoleId"
              placeholder="请选择角色"
              style="width: 100%"
            >
              <el-option
                v-for="role in roleList"
                :key="role.dealerRoleId"
                :label="role.roleName"
                :value="role.dealerRoleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="账号状态" prop="operatorEnabled">
        <el-switch
          v-model="operatorInfo.operatorEnabled"
          :active-value="true"
          :inactive-value="false"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>

      <div class="buttons">
        <el-button @click="handleCancel">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          <template #icon>
            <el-icon><LineMdPlus v-if="!isEdit" /><LineMdEdit v-else /></el-icon>
          </template>
          {{ isEdit ? '修改' : '新增' }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.buttons {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
</style>
